<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\car;


use app\dao\car\CarOccupyTimeDao;
use app\model\car\CarInfo;
use app\model\car\CarOccupyTime;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;

/**
 * Class CarOccupyTimeServices
 * @package app\services\car
 */
class CarOccupyTimeServices extends BaseServices
{
    public function __construct(CarOccupyTimeDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 列表
     * @param array $where
     * @param bool $is_page
     * @return array
     */
    public function getList(array $where = [],bool $is_page = false){
        $page = $limit = 0;
        if($is_page){
            [$page,$limit] = $this->getPageValue();
        }
        $list = $this->dao->getList($where,$page,$limit);
        $occupy_type = [
            'book'=>'预约',
            'offline'=>'线下租车',
            'repair'=>'维修',
            'other'=>'其他',
        ];
        foreach ($list['list'] as &$item){
            $item['occupy_type'] = $occupy_type[$item['occupy_type']];
            $item['start_time'] = date('Y-m-d H:i:s',$item['start_time']);
            $item['end_time'] = date('Y-m-d H:i:s',$item['end_time']);
        }
        return $list;
    }

    /**
     * 保存
     * @param $id
     * @param $data
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function occupyTimeSave($id,$data){
        $car_info = CarInfo::where(['is_del'=>0,'id'=>$data['car_id']])->find();
        $car_info = $car_info ? $car_info->toArray() : [];
        if(!$car_info) throw new AdminException('未查询到车辆信息');
        $start_time = strtotime($data['start_date'].' '.$data['start_time']);
        $end_time = strtotime($data['end_date'].' '.$data['end_time']);
        if($start_time > $end_time) throw new AdminException('开始时间不能大于结束时间');
        // 找出该车型占用相关时间
        $occupy_time = CarOccupyTime::where(['car_id'=>$data['car_id'],'is_del'=>0])->field('id,start_time,end_time')->select()->toArray();
        foreach ($occupy_time as $item){
            if($id != 0 && $id != $item['id']){
                if($item['start_time'] <= $start_time && $item['end_time'] >= $start_time){
                    throw new AdminException('开始时间段已被占用');
                }
                if($item['end_time'] <= $end_time && $item['end_time'] >= $end_time){
                    throw new AdminException('结束时间段已被占用');
                }
            }
        }
        $data['start_time'] = $start_time;
        $data['end_time'] = $end_time;
        if($id){ // 修改
            if($this->dao->update($id,$data)){
                return '修改成功';
            }else{
                throw new AdminException('修改失败或您什么也没修改');
            }
        }else{ // 添加
            isset($data['id']);
            $data['add_time'] = time();
            if($this->dao->save($data)){
                return '添加成功';
            }else{
                throw new AdminException('添加失败');
            }
        }
    }

    /**
     * 获取一条记录
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOccupyTimeInfo($id){
        $occupy_time = $this->dao->get($id);
        $occupy_time = $occupy_time ? $occupy_time->toArray() : [];
        if (!$occupy_time) throw new AdminException('未查询到信息');
        $data = [
            'car_id'=>$occupy_time['car_id'],
            'order_id'=>$occupy_time['order_id'],
            'occupy_type'=>$occupy_time['occupy_type'],
            'start_date'=>date('Y-m-d',$occupy_time['start_time']),
            'start_time'=>date('H:i',$occupy_time['start_time']),
            'end_date'=>date('Y-m-d',$occupy_time['end_time']),
            'end_time'=>date('H:i',$occupy_time['end_time']),
            'remark'=>$occupy_time['remark'],
        ];
        return $data;
    }

    /**
     * 查看详情
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function viewDetailsInfo($data){
        $day = date('t',strtotime($data['year'].'-'.$data['month']));
        $list = CarOccupyTime::where(['is_del'=>0,'car_id'=>$data['car_id']])->whereMonth('end_time',$data['year'].'-'.$data['month'])->select()->toArray();
        $day_list = [];
        if($data['month'] < 10){
            $data['month'] = '0'.$data['month'];
        }
        for($i = 0; $i < $day; $i++){ // 循环天数
            $date = [];
            $day_day = $i+1;
            if($day_day < 10) $day_day = '0'.$day_day;
            $date['date'] = $data['month'].'月'.$day_day.'日';
            for($j = 0; $j < 24; $j++){ // 循环小时
                $day_hour = $j;
                if($day_hour < 10) $day_hour = '0'.$day_hour;
                $day_time = strtotime($data['year'].'-'.$data['month'].'-'.$day_day.' '.$j.':00:00');
                foreach ($list as $item){
                    if($item['start_time'] <= $day_time && $item['end_time'] >= $day_time){
                        if($item['occupy_type'] == 'book'){
                            $date['cellClassName']['time'.$day_hour] = 'book';
                        } else if ($item['occupy_type'] == 'offline'){
                            $date['cellClassName']['time'.$day_hour] = 'offline';
                        } else if ($item['occupy_type'] == 'repair'){
                            $date['cellClassName']['time'.$day_hour] = 'repair';
                        } else if ($item['occupy_type'] == 'other'){
                            $date['cellClassName']['time'.$day_hour] = 'other';
                        }
                    }
                }
            }
            $day_list[] = $date;
        }
        return $day_list;
    }
    /**
     * 删除
     * @param int $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delOccupy(int $id){
        $occupy = $this->dao->get($id);
        if ($occupy) {
            $data['is_del'] = 1;
            $data['delete_time'] = time();
            if (!$this->dao->update($id,$data)) {
                throw new AdminException('删除失败,请稍候再试!');
            }
        }
        return '删除成功!';
    }

    /**
     * 判断车辆是否被占用
     * @param int $car_id
     * @param int $start_time
     * @param int $end_time
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isOccupy(int $car_id,int $start_time,int $end_time,$auto_car){
        $map = [

            ['car_id','=',$car_id],
            ['is_del','=',0],
            ['start_time|end_time','between',[$start_time,$end_time]]
        ];
        if($auto_car){
            $map[] = ['id','<>',$auto_car];
        }
        $occupy = CarOccupyTime::field('id,end_time')->where($map)->select()->toArray();
        foreach($occupy as $k=>$v){
//            $check = $v['end_time'] - $start_time;
//            if($check<600){
//                unset($occupy[$k]);
//            }
            $time = time();
            if($time>$v['end_time']){
             unset($occupy[$k]);
            }
        }
        if($occupy) return true;
        else return false;
    }
}
